package com.om.deadlock;

import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

public class TwoPhilosopherTest {
    private Philosopher westPhilosopher;
    private Philosopher eastPhilosopher;

    @Before
    public void initialize() {
        Fork northFork = new Fork();
        Fork southFork = new Fork();
        westPhilosopher = new Philosopher(northFork, southFork);
        eastPhilosopher = new Philosopher(northFork, southFork);
    }

    private void eat() throws Exception {
        westPhilosopher.eat();
        eastPhilosopher.eat();
        manyTics(Philosopher.EAT_DEADLINE);
    }

    private void manyTics(int count) throws InterruptedException {
        Thread.sleep(1);
        for (int i = 0; i < count; i++) {
            Thread.sleep(1);
            westPhilosopher.tic();
            eastPhilosopher.tic();
        }
    }

    @Test
    public void canEatOnce() throws Exception {
        eat();
        assertTrue(westPhilosopher.isAlive());
        assertTrue(eastPhilosopher.isAlive());
    }

    @Test
    public void canEatManyTimes() throws Exception {
        for (int i = 0; i < 100; i++) {
            eat();
            assertTrue(westPhilosopher.isAlive());
            assertTrue(eastPhilosopher.isAlive());
        }
    }

}
